# -*- coding: utf-8 -*-
import sys

import os
from sqlalchemy import func


base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.utils.tz import utc_to_local_str
from common import orm
from common.transaction.model import TRANSACTION_TYPE
from common.lottery.cyclical import ORDER_STATUS
from common.transaction.db import get_sharding_transaction_table
from common.lottery.cyclical.sd_11x5.model.order import Order as sd_11x5_order

user_id = sys.argv[1]
track_id = sys.argv[2]

transaction_table = get_sharding_transaction_table(user_id)

order_query = sd_11x5_order.query.filter(sd_11x5_order.track_id == track_id).filter(
    sd_11x5_order.status == ORDER_STATUS.CANCEL).all()

total = 0
for item in order_query:
    sum = orm.session.query(func.sum(transaction_table.price)).filter(
        transaction_table.order_id == item.id).scalar()
    if sum != 0:
        print 'order: %s refund failed' % item.id
        total += sum
    else:
        refund_record = transaction_table.query.filter(transaction_table.order_id == item.id). \
            filter(transaction_table.type == TRANSACTION_TYPE.REFUND).first()
        print 'order: %s refund success, transaction id: %s, time: %s' % (
            item.id, refund_record.id, utc_to_local_str(refund_record.updated_at))

print 'total: %s' % total
